﻿using PLCSharp.CoreModel.Prism;
using PLCSharp.Models;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;

namespace PLCSharp.Views.Workflows
{


    [Model]
    public class WorkflowsModel : ModelBase
    {
   
        readonly IContainerExtension Container;
        public WorkflowsModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
        {
            Container = container;
        }


        private ObservableCollection<Workflow> _Workflows = [];
        public ObservableCollection<Workflow> Workflows
        {
            get { return _Workflows; }
            set { SetProperty(ref _Workflows, value); }
        }


        private Workflow _SelectedTask;
        /// <summary>
        /// Comment 
        /// </summary>
        public Workflow SelectedTask
        {
            get { return _SelectedTask; }
            set { SetProperty(ref _SelectedTask, value); }
        }

        private DelegateCommand<string> _Manage;
        public DelegateCommand<string> Manage =>
            _Manage ??= new DelegateCommand<string>(ExecuteManage);

        void ExecuteManage(string cmd)
        {
            switch (cmd)
            {
                case "New":
                    var newTask = new Workflow();
                    newTask.Code =
@"
using System;
using System.Linq;
using System.Collections.ObjectModel;
using PLCSharp.Models;
using PLCSharp.Views.Homepage;
using PLCSharp.CoreModel.Common;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows;
using PLCSharp.CoreModel.UserControls;
public class Extension_" + newTask.ID.ToString().Replace("-", "") +
@" 
{
    public void Run(GlobalModel globalModel,FlowModel flow)
    {
             switch (flow.Step)
            {
                case 0:
                    break;
                case 1:
                    break;
            }
    }
}
";

                    Workflows.Add(newTask);
                   
                    newTask.Start(Container.Resolve<GlobalModel>());
                    break;
                case "Remove":
                    if (SelectedTask != null)
                    {
                        var task = _DatasContext.Workflows.Where(c => c.ID == SelectedTask.ID).FirstOrDefault();
                        if (task != null)
                        {
                            task.Stop();
                            _DatasContext.Workflows.Remove(task);
                            _DatasContext.Save();
                        }
                        var name = SelectedTask.Name;
                        Workflows.Remove(SelectedTask);
                        SendErr($"已删除：{name}", ErrType.ShowDialog);
                      
                    }
                    break;
                case "Save":
                    var names = new List<string>();

                    foreach (var item in Workflows)
                    {
                        if (string.IsNullOrEmpty(item.Name))
                        {
                            SendErr($"保存失败，名称{item.Name}不合适！", ErrType.ShowDialog);
                            return;
                        }

                        if (names.Contains(item.Name))
                        {
                            SendErr($"保存失败，重复的名称{item.Name}！", ErrType.ShowDialog);
                            return;
                        }
                        else
                        {
                            names.Add(item.Name);
                        }
                    }


                    foreach (var item in Workflows)
                    {
                        if (_DatasContext.Workflows.Any(h => h.ID == item.ID) == false)
                        {
                            item.RecipeID = _DatasContext.CurrentRecipe.ID;
                            _DatasContext.Workflows.Add(item);

                        }
                        else
                        {
                            var newitem = _DatasContext.Workflows.Where(c => c.Name == item.Name).FirstOrDefault();
                            newitem.ID = item.ID;
                            newitem.RecipeID = item.RecipeID;
                            newitem.Name = item.Name;
                            newitem.Code = item.Code;
                            newitem.Comment = item.Comment;
                            newitem.AutomaticExecution = item.AutomaticExecution;
                        }


                    }
                    SelectedTask.Prompt = "";
                    _DatasContext.Save();
                    break;

                case "Config":
                    if (editting) return;
                    if (SelectedTask == null) return;
                    if (string.IsNullOrEmpty(SelectedTask.Name)) return;
                    var dialogParams = new DialogParameters
                        {
                            { "SelectedTask", SelectedTask}
                        };
                    editting = true;
                    _dialogService.Show("WorkflowConfig", dialogParams, r =>
                    {
                        editting = false;

                    });
                    break;
            }
        }
        private bool editting;
    }
}
